import cv2
from PIL import Image
import numpy as np

def read_bgr(imgPath):
    img = cv2.imread(imgPath)
    return img

def show_bgr(img):
    cv2.imshow('rgb image',img)
    cv2.waitKey()

#bicubic缩放图片
def resize_bicubic(img,h,w):
    img = cv2.resize(img,(w,h),interpolation=cv2.INTER_CUBIC)
    return img

def save_bgr(img,savePath):
    cv2.imwrite(savePath,img)

#将形状为(channel,H,W)，图片转化为(H,W，channel)
def channel_first_to_last(img):
    img = img.transpose(1,2,0)
    return img

#以rgb格式读取图片文件,channel放在前面，（channel,H,W）
def channel_last_to_first(img):
    img = img.transpose(2,0,1)
    return img





#cv2.flip使用 参考: https://blog.csdn.net/nienelong3319/article/details/95872454
#图片翻转，返回(原图，翻转90度，水平翻转的图片)
def flip(img):
    rotation90 = np.rot90(img) #翻转90度
    horizontal = cv2.flip(img,1) #图像水平翻转
    return (img,rotation90,horizontal)


#progress bar
def print_progress_bar(now,end,barsize=50):
    p = now/end
    bar = "\r["
    bar +="-"*int((barsize*p))
    bar +=">"
    bar +=" "*int(barsize-len(bar))
    bar +="]"
    bar += str(int(p*100))
    bar += "%"
    print(bar,end="")
    
def fill_white(imgPath):
    im = Image.open(imgPath)
    x,y = im.size 
    try: 
        # 使用白色来填充背景 from：www.jb51.net
        # (alpha band as paste mask). 
        p = Image.new('RGBA', im.size, (255,255,255))
        p.paste(im, (0, 0, x, y), im)
        p.save(imgPath)
    except:
        print(imgPath)
        raise


if __name__ == "__main__":
    import os
    png = os.listdir("E:\Datasets\pokemon")
    for p in png:
        try:
            fill_white("E:/Datasets/pokemon/"+p)
            img = read_bgr("E:/Datasets/pokemon/"+p)
            img = resize_bicubic(img,h=324,w=324)
            save_bgr(img, savePath="E:/Datasets/pokemonJPG/"+p.replace("png","jpg"))
        except:
            print(p)
    show_bgr(img)



